'use client';

import { eventCode2Keycode } from "@/src/libs/keycode";
import { KeyCodeInfo } from "@/src/types/types";
import { Input } from "@chakra-ui/react";
import { useEffect, useRef, useState } from "react";

function KeyInput({onChange}: {onChange: (key: KeyCodeInfo) => void}) {
    
    const ref = useRef<HTMLInputElement>(null);
    const [key, setKey] = useState<KeyCodeInfo>({name: ''} as KeyCodeInfo);

    const keyDown = (event: any) => {
        const newKey = {
            name: event.key.toUpperCase()+'',
            code: event.key+'',
            type: 0x20,
            code1: 0,
            code2: eventCode2Keycode(event.code),
            code3: 0,
            lang: "",
        }
        setKey(newKey)
        onChange(newKey)
    }
    
    useEffect(() => {
        ref.current?.addEventListener('keydown', keyDown)
        return () => {
            ref.current?.removeEventListener('keydown', keyDown)
        }
    }, [])

    return (
        <Input ref={ref} value={key?.name} height={"3rem"} w={"18rem"} className="keyinput-box" readOnly={true} />
    );
}

export default KeyInput;